// 引入koa-router
const Router = require('koa2-router');
const router = new Router();

const { timeTrans } = require("../../utils");
const { getLogin } = require("../../model/admin/login");

// 使用token
const { sign, verify } = require("../../utils/token");

/* banner增删改查 */

// 查找users数据
router.post("/", async function (ctx) {
  const { username, password } = ctx.request.body;

  try {
    let data = await getLogin(username);
    // console.log("data", data);
    if (data[0].username === username) {
      if (data[0].password === password) {
        // 生成token
        const token = sign(username);
        // 返回成功信息
        ctx.body = {
          code: 200,
          msg: "登录成功",
          username: data[0].username,
          nickname: data[0].nickname,
          token,
        };
      } else {
        ctx.body = {
          code: 401,
          msg: "登录密码输入错误，请重新输入！",
        };
      }
    } else {
      ctx.body = {
        code: 402,
        msg: "登录用户名输入错误，请重新输入！",
      };
    }
  } catch (error) {
    ctx.body = {
      code: 402,
      msg: "登录用户名输入错误，请重新输入！",
      err: error.message,
    };
  }
});

// 暴露路由
module.exports = router;
